{% extends "xhs/layout.html" %}

{% block title %}小红书数据管理系统 - 数据统计{% endblock %}

{% block page_title %}数据统计{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item active" aria-current="page">数据统计</li>
{% endblock %}

{% block page_actions %}
<div class="d-flex">
    <button class="btn btn-primary me-2" id="refreshStats">
        <i class="fas fa-sync-alt me-1"></i> 刷新数据
    </button>
    <button class="btn btn-outline-primary dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
        <i class="fas fa-file-export me-1"></i> 导出报告
    </button>
    <ul class="dropdown-menu" aria-labelledby="exportDropdown">
        <li><a class="dropdown-item" href="/statistics/export/pdf"><i class="fas fa-file-pdf me-2 text-danger"></i>导出为PDF</a></li>
        <li><a class="dropdown-item" href="/statistics/export/excel"><i class="fas fa-file-excel me-2 text-success"></i>导出为Excel</a></li>
        <li><a class="dropdown-item" href="/statistics/export/image"><i class="fas fa-file-image me-2 text-primary"></i>导出为图片</a></li>
    </ul>
</div>
{% endblock %}

{% block styles %}
{{ super() }}
<style>
    .stat-card {
        border-radius: 0.75rem;
        height: 100%;
        transition: all 0.3s;
        position: relative;
        overflow: hidden;
    }
    
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    
    .stat-card .card-body {
        z-index: 10;
        position: relative;
    }
    
    .stat-card .stat-icon {
        position: absolute;
        top: 15px;
        right: 15px;
        font-size: 1.8rem;
        opacity: 0.2;
        z-index: 0;
    }
    
    .stat-card .stat-title {
        font-size: 0.875rem;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.8);
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    
    .stat-card .stat-value {
        font-size: 2rem;
        font-weight: 700;
        color: #fff;
        margin: 0.25rem 0 0.75rem;
    }
    
    .stat-card .stat-footer {
        display: flex;
        align-items: center;
        font-size: 0.75rem;
        color: rgba(255, 255, 255, 0.8);
    }
    
    .stat-card .stat-badge {
        margin-right: 0.5rem;
        padding: 0.25rem 0.5rem;
        border-radius: 0.375rem;
        font-size: 0.75rem;
        font-weight: 600;
        background-color: rgba(255, 255, 255, 0.2);
    }
    
    .chart-card {
        border-radius: 0.75rem;
        transition: all 0.3s;
        margin-bottom: 1.5rem;
        height: 100%;
    }
    
    .chart-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    
    .chart-card .card-header {
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        background-color: transparent;
        padding: 1rem 1.25rem;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .chart-card .card-header .chart-actions .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
    }
    
    .chart-container {
        height: 350px;
        width: 100%;
        position: relative;
    }
    
    .chart-container .chart-loading {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(255, 255, 255, 0.8);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        z-index: 100;
    }
    
    .chart-container .chart-loading .spinner-border {
        margin-bottom: 0.5rem;
    }
    
    .chart-container .chart-placeholder {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #8898aa;
    }
    
    .date-range-selector {
        display: flex;
        align-items: center;
        margin-bottom: 1.5rem;
        background-color: #fff;
        border-radius: 0.75rem;
        padding: 1rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .date-range-selector .btn-group {
        margin-right: 1rem;
    }
    
    .date-range-selector .btn-group .btn {
        font-size: 0.75rem;
        padding: 0.375rem 0.75rem;
    }
    
    .date-range-selector .custom-date-range {
        display: flex;
        align-items: center;
        max-width: 400px;
    }
    
    .date-range-selector .custom-date-range input {
        max-width: 150px;
    }
    
    .date-range-selector .custom-date-range span {
        margin: 0 0.5rem;
    }
    
    @media (max-width: 767.98px) {
        .date-range-selector {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .date-range-selector .btn-group {
            margin-right: 0;
            margin-bottom: 1rem;
            width: 100%;
        }
        
        .date-range-selector .custom-date-range {
            width: 100%;
            max-width: 100%;
        }
    }
    
    .word-cloud-container {
        width: 100%;
        height: 350px;
        position: relative;
    }
    
    .trend-card {
        height: calc(100% - 1.5rem);
    }
    
    .trend-card .trend-item {
        display: flex;
        align-items: center;
        padding: 0.75rem 0;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }
    
    .trend-card .trend-item:last-child {
        border-bottom: none;
    }
    
    .trend-card .trend-item .trend-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 1rem;
        color: #fff;
    }
    
    .trend-card .trend-item .trend-info {
        flex: 1;
    }
    
    .trend-card .trend-item .trend-title {
        font-weight: 600;
        margin-bottom: 0.25rem;
    }
    
    .trend-card .trend-item .trend-details {
        font-size: 0.75rem;
        color: #8898aa;
    }
    
    .trend-card .trend-item .trend-value {
        font-weight: 700;
        font-size: 1.25rem;
    }
    
    .table-responsive {
        border-radius: 0.375rem;
        overflow: hidden;
    }
</style>
{% endblock %}

{% block content %}
<!-- 日期范围选择器 -->
<div class="date-range-selector animate__animated animate__fadeIn">
    <div class="btn-group" role="group">
        <button type="button" class="btn btn-outline-primary active" id="range-7d" style="writing-mode: horizontal-tb; white-space: nowrap; word-break: keep-all; word-wrap: normal;">最近7天</button>
        <button type="button" class="btn btn-outline-primary" id="range-30d" style="writing-mode: horizontal-tb; white-space: nowrap; word-break: keep-all; word-wrap: normal;">最近30天</button>
        <button type="button" class="btn btn-outline-primary" id="range-90d" style="writing-mode: horizontal-tb; white-space: nowrap; word-break: keep-all; word-wrap: normal;">最近90天</button>
        <button type="button" class="btn btn-outline-primary" id="range-all" style="writing-mode: horizontal-tb; white-space: nowrap; word-break: keep-all; word-wrap: normal;">全部</button>
    </div>
    <div class="custom-date-range ms-auto" style="display: flex; align-items: center;width: 90%;margin-right: 130px;">
        <label class="me-2" style="width: 100px; display: inline-block; writing-mode: horizontal-tb; text-orientation: mixed; white-space: nowrap; word-break: keep-all; word-wrap: normal;">自定义范围:</label>
        <input type="date" class="form-control" id="date-from" style="writing-mode: horizontal-tb; white-space: nowrap;">
        <span class="mx-2" style="writing-mode: horizontal-tb; text-orientation: mixed; white-space: nowrap; word-break: keep-all; word-wrap: normal;">至</span>
        <input type="date" class="form-control" id="date-to" style="writing-mode: horizontal-tb; white-space: nowrap;">
        <button class="btn btn-primary ms-2" id="apply-custom-range" style="writing-mode: horizontal-tb; text-orientation: mixed; white-space: nowrap; word-break: keep-all; word-wrap: normal;">应用</button>
    </div>
</div>

<!-- 数据概览卡片 -->
<div class="row g-3 mb-4">
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card animate__animated animate__fadeInUp animate__delay-1s" style="background: linear-gradient(45deg, #FF4F5E, #FF7B6E);">
            <div class="card-body">
                <div class="stat-icon">
                    <i class="fas fa-tasks"></i>
                </div>
                <div class="stat-title">采集任务</div>
                <div class="stat-value">{{ stats.tasks_count }}</div>
                <div class="stat-footer">
                    <div class="stat-badge">
                        <i class="fas fa-arrow-up me-1"></i> 12%
                    </div>
                    <span>相比上月</span>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card animate__animated animate__fadeInUp animate__delay-2s" style="background: linear-gradient(45deg, #2DCE89, #2EECA7);">
            <div class="card-body">
                <div class="stat-icon">
                    <i class="fas fa-book-open"></i>
                </div>
                <div class="stat-title">笔记数量</div>
                <div class="stat-value">{{ stats.notes_count }}</div>
                <div class="stat-footer">
                    <div class="stat-badge">
                        <i class="fas fa-arrow-up me-1"></i> 25%
                    </div>
                    <span>相比上月</span>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card animate__animated animate__fadeInUp animate__delay-3s" style="background: linear-gradient(45deg, #11CDEF, #1BE4FF);">
            <div class="card-body">
                <div class="stat-icon">
                    <i class="fas fa-comments"></i>
                </div>
                <div class="stat-title">评论数量</div>
                <div class="stat-value">{{ stats.comments_count }}</div>
                <div class="stat-footer">
                    <div class="stat-badge">
                        <i class="fas fa-arrow-up me-1"></i> 18%
                    </div>
                    <span>相比上月</span>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card animate__animated animate__fadeInUp animate__delay-4s" style="background: linear-gradient(45deg, #6A7BFF, #8B97FF);">
            <div class="card-body">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-title">用户数量</div>
                <div class="stat-value">{{ stats.users_count }}</div>
                <div class="stat-footer">
                    <div class="stat-badge">
                        <i class="fas fa-arrow-up me-1"></i> 15%
                    </div>
                    <span>相比上月</span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 任务状态分布 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-chart-pie text-primary me-2"></i>
                    任务状态分布
                </div>
                <div class="chart-actions">
                    <button class="btn btn-sm btn-outline-secondary" id="refresh-task-status">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-secondary" id="download-task-status">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="taskStatusChart" class="chart-container"></div>
            </div>
        </div>
    </div>
    
    <!-- 笔记点赞数量分布 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-heart text-danger me-2"></i>
                    笔记点赞数量分布
                </div>
                <div class="chart-actions">
                    <button class="btn btn-sm btn-outline-secondary" id="refresh-notes-likes">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-secondary" id="download-notes-likes">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="noteLikesChart" class="chart-container"></div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 用户地理位置分布 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-map-marker-alt text-primary me-2"></i>
                    用户地理位置分布
                </div>
                <div class="chart-actions">
                    <div class="btn-group">
                        <button class="btn btn-sm btn-outline-secondary active" id="view-pie">
                            <i class="fas fa-chart-pie"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" id="view-map">
                            <i class="fas fa-map"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="locationChart" class="chart-container"></div>
            </div>
        </div>
    </div>
    
    <!-- 采集数据趋势 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-chart-line text-success me-2"></i>
                    采集数据趋势
                </div>
                <div class="chart-actions">
                    <div class="btn-group">
                        <button class="btn btn-sm btn-outline-secondary active" id="trend-daily">日</button>
                        <button class="btn btn-sm btn-outline-secondary" id="trend-weekly">周</button>
                        <button class="btn btn-sm btn-outline-secondary" id="trend-monthly">月</button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="dataCollectionTrendChart" class="chart-container"></div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 热门关键词 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-tags text-primary me-2"></i>
                    热门关键词
                </div>
                <div class="chart-actions">
                    <select class="form-select form-select-sm" id="word-cloud-type" style="width: auto;">
                        <option value="keywords">关键词</option>
                        <option value="titles">标题词频</option>
                        <option value="comments">评论词频</option>
                    </select>
                </div>
            </div>
            <div class="card-body">
                <div id="keywordCloud" class="chart-container"></div>
            </div>
        </div>
    </div>
    
    <!-- 笔记评论互动分析 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-chart-bar text-info me-2"></i>
                    笔记互动分析
                </div>
                <div class="chart-actions">
                    <div class="btn-group">
                        <button class="btn btn-sm btn-outline-secondary active" id="interaction-bar">柱状图</button>
                        <button class="btn btn-sm btn-outline-secondary" id="interaction-radar">雷达图</button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="interactionsChart" class="chart-container"></div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 热门笔记排行 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-fire text-warning me-2"></i>
                    热门笔记排行
                </div>
                <div class="chart-actions">
                    <select class="form-select form-select-sm" id="hot-notes-metric" style="width: auto;">
                        <option value="likes">按点赞数</option>
                        <option value="collects">按收藏数</option>
                        <option value="comments">按评论数</option>
                    </select>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th style="width: 5%">排名</th>
                                <th style="width: 45%">标题</th>
                                <th style="width: 15%">作者</th>
                                <th style="width: 10%">点赞</th>
                                <th style="width: 10%">收藏</th>
                                <th style="width: 15%">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for i in range(1, 6) %}
                            <tr>
                                <td>
                                    <span class="badge bg-{{ 'primary' if i == 1 else ('success' if i == 2 else ('info' if i == 3 else 'secondary')) }}">{{ i }}</span>
                                </td>
                                <td>
                                    <a href="#" class="text-dark fw-500 d-block text-truncate">
                                        示例热门笔记标题 {{ i }}
                                    </a>
                                </td>
                                <td>用户{{ i }}</td>
                                <td>{{ (stats.notes_count / i)|round|int }}</td>
                                <td>{{ (stats.notes_count / (i + 1))|round|int }}</td>
                                <td>
                                    <a href="#" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye me-1"></i>查看
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 活跃用户排行 -->
    <div class="col-lg-6">
        <div class="card chart-card">
            <div class="card-header">
                <div>
                    <i class="fas fa-user-friends text-danger me-2"></i>
                    活跃用户排行
                </div>
                <div class="chart-actions">
                    <select class="form-select form-select-sm" id="active-users-metric" style="width: auto;">
                        <option value="notes">按笔记数</option>
                        <option value="likes">按获赞数</option>
                        <option value="fans">按粉丝数</option>
                    </select>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th style="width: 5%">排名</th>
                                <th style="width: 20%">用户</th>
                                <th style="width: 20%">笔记数</th>
                                <th style="width: 20%">获赞总数</th>
                                <th style="width: 20%">粉丝数</th>
                                <th style="width: 15%">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for i in range(1, 6) %}
                            <tr>
                                <td>
                                    <span class="badge bg-{{ 'primary' if i == 1 else ('success' if i == 2 else ('info' if i == 3 else 'secondary')) }}">{{ i }}</span>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-circle me-2" style="width: 32px; height: 32px; background-color: var(--primary-color); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white;">
                                            <i class="fas fa-user"></i>
                                        </div>
                                        <div>用户{{ i }}</div>
                                    </div>
                                </td>
                                <td>{{ (50 / i)|round|int }}</td>
                                <td>{{ (stats.notes_count * 10 / i)|round|int }}</td>
                                <td>{{ (stats.users_count * 5 / i)|round|int }}</td>
                                <td>
                                    <a href="#" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye me-1"></i>查看
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有图表
    initCharts();
    
    // 初始化日期选择器
    initDateRangeSelector();
    
    // 绑定刷新事件
    document.getElementById('refreshStats').addEventListener('click', function() {
        refreshAllCharts();
    });
    
    // 绑定导出事件
    document.querySelectorAll('[id^="download-"]').forEach(function(btn) {
        btn.addEventListener('click', function() {
            downloadChart(btn.id.replace('download-', ''));
        });
    });
    
    // 图表视图切换事件
    document.getElementById('view-pie').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('view-map').classList.remove('active');
        updateLocationChartView('pie');
    });
    
    document.getElementById('view-map').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('view-pie').classList.remove('active');
        updateLocationChartView('map');
    });
    
    // 趋势图周期切换
    document.getElementById('trend-daily').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('trend-weekly').classList.remove('active');
        document.getElementById('trend-monthly').classList.remove('active');
        updateTrendChartPeriod('daily');
    });
    
    document.getElementById('trend-weekly').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('trend-daily').classList.remove('active');
        document.getElementById('trend-monthly').classList.remove('active');
        updateTrendChartPeriod('weekly');
    });
    
    document.getElementById('trend-monthly').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('trend-daily').classList.remove('active');
        document.getElementById('trend-weekly').classList.remove('active');
        updateTrendChartPeriod('monthly');
    });
    
    // 互动图表类型切换
    document.getElementById('interaction-bar').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('interaction-radar').classList.remove('active');
        updateInteractionsChartType('bar');
    });
    
    document.getElementById('interaction-radar').addEventListener('click', function() {
        this.classList.add('active');
        document.getElementById('interaction-bar').classList.remove('active');
        updateInteractionsChartType('radar');
    });
    
    // 词云类型切换
    document.getElementById('word-cloud-type').addEventListener('change', function() {
        updateWordCloudType(this.value);
    });
    
    // 热门笔记指标切换
    document.getElementById('hot-notes-metric').addEventListener('change', function() {
        updateHotNotesMetric(this.value);
    });
    
    // 活跃用户指标切换
    document.getElementById('active-users-metric').addEventListener('change', function() {
        updateActiveUsersMetric(this.value);
    });
});

// 初始化所有图表
function initCharts() {
    // 任务状态分布图
    var taskStatusChart = echarts.init(document.getElementById('taskStatusChart'));
    taskStatusChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: '5%',
            top: 'center',
            data: ['已完成', '进行中', '失败', '待执行']
        },
        series: [
            {
                name: '任务状态',
                type: 'pie',
                radius: ['45%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: {{ stats.task_status.success|default(0) }}, name: '已完成', itemStyle: { color: '#2DCE89' } },
                    { value: {{ stats.task_status.running|default(0) }}, name: '进行中', itemStyle: { color: '#FB6340' } },
                    { value: {{ stats.task_status.failed|default(0) }}, name: '失败', itemStyle: { color: '#F5365C' } },
                    { value: {{ stats.task_status.pending|default(0) }}, name: '待执行', itemStyle: { color: '#11CDEF' } }
                ]
            }
        ]
    });

    // 笔记点赞数量分布
    var noteLikesChart = echarts.init(document.getElementById('noteLikesChart'));
    noteLikesChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: {{ stats.likes_distribution.ranges|default(['0-100', '101-500', '501-1000', '1001-5000', '5000+'])|safe }},
            axisLabel: {
                interval: 0,
                rotate: 30,
                color: '#8898aa'
            },
            axisLine: {
                lineStyle: {
                    color: '#ced4da'
                }
            }
        },
        yAxis: {
            type: 'value',
            name: '笔记数量',
            nameTextStyle: {
                color: '#8898aa'
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#ced4da'
                }
            },
            axisLabel: {
                color: '#8898aa'
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(0,0,0,0.05)'
                }
            }
        },
        series: [{
            name: '笔记数量',
            type: 'bar',
            barWidth: '60%',
            data: {{ stats.likes_distribution.counts|default([150, 80, 45, 20, 5])|safe }},
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#FF4F5E'},
                    {offset: 1, color: '#FF7B6E'}
                ])
            }
        }]
    });

    // 用户地理位置分布
    var locationChart = echarts.init(document.getElementById('locationChart'));
    locationChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            textStyle: {
                color: '#8898aa'
            }
        },
        series: [
            {
                name: '地理位置',
                type: 'pie',
                radius: '60%',
                center: ['40%', '50%'],
                data: {{ stats.location_distribution|default([
                    {name: '北京', value: 50},
                    {name: '上海', value: 80},
                    {name: '广州', value: 60},
                    {name: '深圳', value: 70},
                    {name: '杭州', value: 40},
                    {name: '成都', value: 30},
                    {name: '武汉', value: 20},
                    {name: '其他', value: 50}
                ])|safe }},
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                label: {
                    show: false
                },
                itemStyle: {
                    borderRadius: 5,
                    borderColor: '#fff',
                    borderWidth: 2
                }
            }
        ]
    });

    // 采集数据趋势
    var dataCollectionTrendChart = echarts.init(document.getElementById('dataCollectionTrendChart'));
    dataCollectionTrendChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        legend: {
            data: ['笔记', '评论'],
            right: '5%',
            textStyle: {
                color: '#8898aa'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: {{ stats.collection_trend.dates|default(['1月', '2月', '3月', '4月', '5月', '6月', '7月'])|safe }},
                axisLabel: {
                    color: '#8898aa'
                },
                axisLine: {
                    lineStyle: {
                        color: '#ced4da'
                    }
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    color: '#8898aa'
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#ced4da'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(0,0,0,0.05)'
                    }
                }
            }
        ],
        series: [
            {
                name: '笔记',
                type: 'line',
                stack: 'Total',
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#2DCE89'
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.2,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: 'rgba(45, 206, 137, 0.5)'},
                        {offset: 1, color: 'rgba(45, 206, 137, 0.1)'}
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: {{ stats.collection_trend.notes|default([120, 132, 101, 134, 90, 180, 210])|safe }}
            },
            {
                name: '评论',
                type: 'line',
                stack: 'Total',
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#11CDEF'
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.2,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: 'rgba(17, 205, 239, 0.5)'},
                        {offset: 1, color: 'rgba(17, 205, 239, 0.1)'}
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: {{ stats.collection_trend.comments|default([220, 182, 191, 234, 290, 330, 310])|safe }}
            }
        ]
    });
    
    // 热门关键词词云
    var keywordCloud = echarts.init(document.getElementById('keywordCloud'));
    keywordCloud.setOption({
        tooltip: {
            show: true
        },
        series: [{
            type: 'wordCloud',
            shape: 'circle',
            left: 'center',
            top: 'center',
            width: '90%',
            height: '90%',
            right: null,
            bottom: null,
            sizeRange: [12, 35],
            rotationRange: [-45, 45],
            rotationStep: 5,
            gridSize: 8,
            drawOutOfBound: false,
            textStyle: {
                fontFamily: 'sans-serif',
                fontWeight: 'bold',
                color: function () {
                    // 随机颜色
                    return 'rgb(' + [
                        Math.round(Math.random() * 200 + 55),
                        Math.round(Math.random() * 200 + 55),
                        Math.round(Math.random() * 200 + 55)
                    ].join(',') + ')';
                }
            },
            emphasis: {
                focus: 'self',
                textStyle: {
                    shadowBlur: 10,
                    shadowColor: '#333'
                }
            },
            data: {{ stats.keywords_cloud|default([
                {name: '旅行', value: 100},
                {name: '美食', value: 80},
                {name: '穿搭', value: 75},
                {name: '摄影', value: 70},
                {name: '护肤', value: 65},
                {name: '时尚', value: 60},
                {name: '彩妆', value: 55},
                {name: '读书', value: 50},
                {name: '减肥', value: 45},
                {name: '健身', value: 40},
                {name: '宠物', value: 35},
                {name: '家居', value: 30},
                {name: '音乐', value: 25},
                {name: '电影', value: 20},
                {name: '育儿', value: 15}
            ])|safe }}
        }]
    });
    
    // 笔记互动分析
    var interactionsChart = echarts.init(document.getElementById('interactionsChart'));
    interactionsChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['点赞数', '收藏数', '评论数'],
            right: '5%',
            textStyle: {
                color: '#8898aa'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: {{ stats.interactions.categories|default(['美食', '旅行', '穿搭', '美妆', '数码'])|safe }},
            axisLabel: {
                interval: 0,
                rotate: 30,
                color: '#8898aa'
            },
            axisLine: {
                lineStyle: {
                    color: '#ced4da'
                }
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                color: '#8898aa'
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#ced4da'
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(0,0,0,0.05)'
                }
            }
        },
        series: [
            {
                name: '点赞数',
                type: 'bar',
                barGap: 0,
                emphasis: {
                    focus: 'series'
                },
                data: {{ stats.interactions.likes|default([120, 200, 150, 80, 70])|safe }},
                itemStyle: {
                    color: '#FF4F5E'
                }
            },
            {
                name: '收藏数',
                type: 'bar',
                emphasis: {
                    focus: 'series'
                },
                data: {{ stats.interactions.collects|default([80, 150, 100, 50, 40])|safe }},
                itemStyle: {
                    color: '#6A7BFF'
                }
            },
            {
                name: '评论数',
                type: 'bar',
                emphasis: {
                    focus: 'series'
                },
                data: {{ stats.interactions.comments|default([40, 80, 50, 30, 20])|safe }},
                itemStyle: {
                    color: '#2DCE89'
                }
            }
        ]
    });
    
    // 窗口大小变化时自动调整图表大小
    window.addEventListener('resize', function() {
        taskStatusChart.resize();
        noteLikesChart.resize();
        locationChart.resize();
        dataCollectionTrendChart.resize();
        keywordCloud.resize();
        interactionsChart.resize();
    });
}

// 初始化日期范围选择器
function initDateRangeSelector() {
    // 设置默认日期（今天）
    var today = new Date();
    var dateTo = document.getElementById('date-to');
    dateTo.valueAsDate = today;
    
    // 设置默认起始日期（7天前）
    var sevenDaysAgo = new Date(today);
    sevenDaysAgo.setDate(today.getDate() - 7);
    var dateFrom = document.getElementById('date-from');
    dateFrom.valueAsDate = sevenDaysAgo;
    
    // 日期范围按钮事件
    document.getElementById('range-7d').addEventListener('click', function() {
        setActiveRangeButton(this);
        setDateRange(7);
    });
    
    document.getElementById('range-30d').addEventListener('click', function() {
        setActiveRangeButton(this);
        setDateRange(30);
    });
    
    document.getElementById('range-90d').addEventListener('click', function() {
        setActiveRangeButton(this);
        setDateRange(90);
    });
    
    document.getElementById('range-all').addEventListener('click', function() {
        setActiveRangeButton(this);
        // 设置一个很早的日期作为开始日期
        var earlyDate = new Date(2020, 0, 1);
        dateFrom.valueAsDate = earlyDate;
        refreshAllCharts();
    });
    
    // 应用自定义范围
    document.getElementById('apply-custom-range').addEventListener('click', function() {
        clearActiveRangeButton();
        refreshAllCharts();
    });
}

// 设置活动的范围按钮
function setActiveRangeButton(button) {
    document.querySelectorAll('.date-range-selector .btn-group .btn').forEach(function(btn) {
        btn.classList.remove('active');
    });
    button.classList.add('active');
}

// 清除活动的范围按钮
function clearActiveRangeButton() {
    document.querySelectorAll('.date-range-selector .btn-group .btn').forEach(function(btn) {
        btn.classList.remove('active');
    });
}

// 设置日期范围
function setDateRange(days) {
    var today = new Date();
    var dateTo = document.getElementById('date-to');
    dateTo.valueAsDate = today;
    
    var fromDate = new Date(today);
    fromDate.setDate(today.getDate() - days);
    var dateFrom = document.getElementById('date-from');
    dateFrom.valueAsDate = fromDate;
    
    refreshAllCharts();
}

// 刷新所有图表
function refreshAllCharts() {
    // 这里应该是发送AJAX请求获取新数据，然后更新图表
    // 为演示目的，我们只显示加载动画
    
    // 显示加载状态
    showLoadingForAllCharts();
    
    // 模拟加载时间
    setTimeout(function() {
        // 隐藏加载状态
        hideLoadingForAllCharts();
        
        // 显示成功消息
        showToast('数据刷新成功', 'success');
    }, 1500);
}

// 为所有图表显示加载状态
function showLoadingForAllCharts() {
    var chartIds = ['taskStatusChart', 'noteLikesChart', 'locationChart', 
                   'dataCollectionTrendChart', 'keywordCloud', 'interactionsChart'];
    
    chartIds.forEach(function(id) {
        var chart = echarts.getInstanceByDom(document.getElementById(id));
        if (chart) {
            chart.showLoading({
                text: '数据加载中...',
                color: '#FF4F5E',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            });
        }
    });
}

// 为所有图表隐藏加载状态
function hideLoadingForAllCharts() {
    var chartIds = ['taskStatusChart', 'noteLikesChart', 'locationChart', 
                   'dataCollectionTrendChart', 'keywordCloud', 'interactionsChart'];
    
    chartIds.forEach(function(id) {
        var chart = echarts.getInstanceByDom(document.getElementById(id));
        if (chart) {
            chart.hideLoading();
        }
    });
}

// 显示提示消息
function showToast(message, type) {
    // 创建一个toast元素
    var toast = document.createElement('div');
    toast.className = 'toast show';
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    var toastHeader = document.createElement('div');
    toastHeader.className = 'toast-header';
    
    var toastTitle = document.createElement('span');
    toastTitle.className = 'me-auto text-' + type;
    
    var icon = document.createElement('i');
    if (type === 'success') {
        icon.className = 'fas fa-check-circle me-1';
    } else if (type === 'danger') {
        icon.className = 'fas fa-exclamation-circle me-1';
    } else if (type === 'warning') {
        icon.className = 'fas fa-exclamation-triangle me-1';
    } else {
        icon.className = 'fas fa-info-circle me-1';
    }
    
    toastTitle.appendChild(icon);
    toastTitle.appendChild(document.createTextNode('提示信息'));
    
    var closeButton = document.createElement('button');
    closeButton.className = 'btn-close';
    closeButton.setAttribute('type', 'button');
    closeButton.setAttribute('data-bs-dismiss', 'toast');
    closeButton.setAttribute('aria-label', 'Close');
    
    toastHeader.appendChild(toastTitle);
    toastHeader.appendChild(closeButton);
    
    var toastBody = document.createElement('div');
    toastBody.className = 'toast-body';
    toastBody.textContent = message;
    
    toast.appendChild(toastHeader);
    toast.appendChild(toastBody);
    
    // 查找或创建toast容器
    var toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        document.body.appendChild(toastContainer);
    }
    
    // 添加toast到容器
    toastContainer.appendChild(toast);
    
    // 创建Bootstrap的Toast实例
    var bsToast = new bootstrap.Toast(toast, {
        delay: 3000
    });
    
    // 显示toast
    bsToast.show();
    
    // 监听隐藏事件，当toast隐藏后从DOM中移除
    toast.addEventListener('hidden.bs.toast', function() {
        toast.remove();
    });
}

// 更新位置图表视图类型
function updateLocationChartView(viewType) {
    var locationChart = echarts.getInstanceByDom(document.getElementById('locationChart'));
    if (!locationChart) return;
    
    if (viewType === 'map') {
        // 加载中国地图
        locationChart.showLoading();
        
        // 模拟异步加载地图数据
        setTimeout(function() {
            locationChart.hideLoading();
            // 这里需要先加载中国地图数据，实际项目中可以使用AJAX加载
            // 为了简化，我们保持使用饼图
            showToast('地图数据加载成功', 'success');
        }, 1000);
    } else {
        // 恢复饼图
        locationChart.setOption({
            series: [
                {
                    type: 'pie',
                    radius: '60%'
                }
            ]
        });
    }
}

// 更新趋势图周期
function updateTrendChartPeriod(period) {
    var trendChart = echarts.getInstanceByDom(document.getElementById('dataCollectionTrendChart'));
    if (!trendChart) return;
    
    trendChart.showLoading();
    
    // 模拟数据加载
    setTimeout(function() {
        trendChart.hideLoading();
        
        var dates, notesData, commentsData;
        
        if (period === 'daily') {
            dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            notesData = [30, 40, 35, 50, 60, 70, 90];
            commentsData = [70, 60, 65, 80, 100, 120, 150];
        } else if (period === 'weekly') {
            dates = ['第1周', '第2周', '第3周', '第4周'];
            notesData = [200, 250, 300, 350];
            commentsData = [400, 450, 500, 550];
        } else if (period === 'monthly') {
            dates = ['1月', '2月', '3月', '4月', '5月', '6月'];
            notesData = [800, 900, 1000, 1100, 1200, 1300];
            commentsData = [1500, 1600, 1700, 1800, 1900, 2000];
        }
        
        trendChart.setOption({
            xAxis: {
                data: dates
            },
            series: [
                {
                    name: '笔记',
                    data: notesData
                },
                {
                    name: '评论',
                    data: commentsData
                }
            ]
        });
    }, 800);
}

// 更新互动图表类型
function updateInteractionsChartType(chartType) {
    var interactionsChart = echarts.getInstanceByDom(document.getElementById('interactionsChart'));
    if (!interactionsChart) return;
    
    interactionsChart.showLoading();
    
    setTimeout(function() {
        interactionsChart.hideLoading();
        
        if (chartType === 'radar') {
            interactionsChart.setOption({
                radar: {
                    indicator: [
                        { name: '美食', max: 300 },
                        { name: '旅行', max: 300 },
                        { name: '穿搭', max: 300 },
                        { name: '美妆', max: 300 },
                        { name: '数码', max: 300 }
                    ],
                    radius: '60%'
                },
                series: [{
                    type: 'radar',
                    name: '互动分析',
                    data: [
                        {
                            value: [120, 200, 150, 80, 70],
                            name: '点赞数',
                            areaStyle: {
                                color: 'rgba(255, 79, 94, 0.3)'
                            },
                            lineStyle: {
                                color: '#FF4F5E'
                            }
                        },
                        {
                            value: [80, 150, 100, 50, 40],
                            name: '收藏数',
                            areaStyle: {
                                color: 'rgba(106, 123, 255, 0.3)'
                            },
                            lineStyle: {
                                color: '#6A7BFF'
                            }
                        },
                        {
                            value: [40, 80, 50, 30, 20],
                            name: '评论数',
                            areaStyle: {
                                color: 'rgba(45, 206, 137, 0.3)'
                            },
                            lineStyle: {
                                color: '#2DCE89'
                            }
                        }
                    ]
                }]
            });
        } else {
            interactionsChart.setOption({
                xAxis: {
                    type: 'category',
                    data: ['美食', '旅行', '穿搭', '美妆', '数码']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '点赞数',
                        type: 'bar',
                        data: [120, 200, 150, 80, 70],
                        itemStyle: {
                            color: '#FF4F5E'
                        }
                    },
                    {
                        name: '收藏数',
                        type: 'bar',
                        data: [80, 150, 100, 50, 40],
                        itemStyle: {
                            color: '#6A7BFF'
                        }
                    },
                    {
                        name: '评论数',
                        type: 'bar',
                        data: [40, 80, 50, 30, 20],
                        itemStyle: {
                            color: '#2DCE89'
                        }
                    }
                ]
            });
        }
    }, 800);
}

// 更新词云类型
function updateWordCloudType(type) {
    var keywordCloud = echarts.getInstanceByDom(document.getElementById('keywordCloud'));
    if (!keywordCloud) return;
    
    keywordCloud.showLoading();
    
    setTimeout(function() {
        keywordCloud.hideLoading();
        
        var cloudData;
        
        if (type === 'keywords') {
            cloudData = [
                {name: '旅行', value: 100},
                {name: '美食', value: 80},
                {name: '穿搭', value: 75},
                {name: '摄影', value: 70},
                {name: '护肤', value: 65},
                {name: '时尚', value: 60},
                {name: '彩妆', value: 55},
                {name: '读书', value: 50},
                {name: '减肥', value: 45},
                {name: '健身', value: 40}
            ];
        } else if (type === 'titles') {
            cloudData = [
                {name: '推荐', value: 90},
                {name: '分享', value: 85},
                {name: '教程', value: 80},
                {name: '攻略', value: 75},
                {name: '必买', value: 70},
                {name: '测评', value: 65},
                {name: '探店', value: 60},
                {name: '种草', value: 55},
                {name: '美食', value: 50},
                {name: '旅行', value: 45}
            ];
        } else if (type === 'comments') {
            cloudData = [
                {name: '好看', value: 90},
                {name: '喜欢', value: 85},
                {name: '太棒了', value: 80},
                {name: '谢谢分享', value: 75},
                {name: '支持', value: 70},
                {name: '不错', value: 65},
                {name: '很美', value: 60},
                {name: '推荐', value: 55},
                {name: '学习了', value: 50},
                {name: '点赞', value: 45}
            ];
        }
        
        keywordCloud.setOption({
            series: [{
                data: cloudData
            }]
        });
    }, 800);
}

// 下载图表为图片
function downloadChart(chartId) {
    var chart = echarts.getInstanceByDom(document.getElementById(chartId + 'Chart'));
    if (!chart) return;
    
    var url = chart.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
    });
    
    var link = document.createElement('a');
    link.href = url;
    link.download = chartId + '_' + new Date().toISOString().slice(0, 10) + '.png';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>
{% endblock %} 